<?php

namespace App\Http\Controllers;

use App\Events\Kickout;
use App\Models\Buy;
use App\Models\Member;
use App\Models\Sell;
use App\Models\User;
use App\Models\Violation;
use Illuminate\Http\Request;

class MemberController extends Controller
{
  public function index(Request $request)
  {
    $page = User::select('id', 'pid', 'username', 'mobile', 'coins', 'fee_ratio', 'tip', 'created_at', 'login_at', 'login_ip', 'enable', 'realname')
      ->with('parent:id,code,username')
      ->withCount('violations')
      ->when($request->has('parent_username'), function ($q) use ($request) {
        $q->whereHas('parent', function ($q) use ($request) {
          $q->where('username', $request->parent_username);
        });
      })
      ->when($request->has('username'), function ($q) use ($request) {
        $q->where('username', $request->username);
      })
      ->when($request->has('mobile'), function ($q) use ($request) {
        $q->where('mobile', $request->mobile);
      })
      ->when($request->has('created_at'), function ($q) use ($request) {
        $range = getRange($request->created_at);
        $q->whereBetween('created_at', $range);
      })
      ->where('role', 'member')
      ->latest()
      ->page();

    return success($page);
  }

  public function indexForAgent(Request $request)
  {
    $page = User::select('id', 'username', 'mobile', 'coins', 'fee_ratio', 'tip', 'created_at', 'updated_at', 'login_at', 'enable')
      ->withCount('violations')
      ->when($request->has('created_at'), function ($q) use ($request) {
        $range = getRange($request->created_at);
        $q->whereBetween('created_at', $range);
      })
      ->when($request->has('username'), function ($q) use ($request) {
        $q->where('username', $request->username);
      })
      ->where('pid', auth()->id())
      ->latest()
      ->page();

    return success($page);
  }

  public function accounts(Request $request)
  {
    $page = $this->accountQueryBuilder($request)
      ->latest()
      ->page();

    $page->transform(function ($item) {
      $item->buys_frozen_sum_deposit = 0 + $item->buys_frozen_sum_deposit;
      $item->solds_sum_coins = 0 + $item->solds_sum_coins;
      $item->boughts_sum_coins = 0 + $item->boughts_sum_coins;
      $item->boughts_sum_tip = 0 + $item->boughts_sum_tip;
      $item->boughts_sum_fee = 0 + $item->boughts_sum_fee;
      return $item;
    });

    $all = $this->accountQueryBuilder($request)->get();

    $footer = [
      '汇总',
      '',
      (int) $all->sum('violations_count'),
    ];

    $sums = [
      'coins', //可动币
      'buys_frozen_sum_deposit', //担保币
      'solds_sum_coins', //卖出
      'boughts_sum_coins',  //买入
      'boughts_sum_fee', //收益
      'boughts_sum_tip' //奖励
    ];

    foreach ($sums as $name) {
      $num = $all->sum($name);
      $footer[] = (float) $num;
    }

    return success($page, $footer);
  }

  protected function accountQueryBuilder($request)
  {
    return User::select('id', 'username', 'coins')
      ->when($request->has('username'), function ($q) use ($request) {
        $q->where('username', $request->username);
      })
      ->when($request->has('created_at'), function ($q) use ($request) {
        $range = getRange($request->created_at);

        $q->withSumBetween('buysFrozen', 'deposit', $range, 'updated_at')
          ->withSumBetween('solds', 'coins', $range, 'updated_at')
          ->withSumBetween('boughts', 'coins', $range, 'updated_at')
          ->withSumBetween('boughts', 'tip', $range, 'updated_at')
          ->withSumBetween('boughts', 'fee', $range, 'updated_at')
          ->withCountBetween('violations', $range, 'updated_at');
      }, function ($q) {
        $q->withSum('buysFrozen', 'deposit')
          ->withSum('solds', 'coins')
          ->withSum('boughts', 'coins')
          ->withSum('boughts', 'fee')
          ->withSum('boughts', 'tip')
          ->withCount('violations');
      })
      ->where('role', 'member');
  }

  public function adjust(Request $request, $id)
  {
    $member = User::findOrFail($id);
    if ($member->pid !== auth()->id()) {
      forbidden();
    }
    $agent = auth()->user();
    if ($request->fee_ratio > $agent->fee_ratio) {
      fail('佣金比例错误');
    }
    if ($request->tip > $agent->tip) {
      fail('奖励错误');
    }
    $member->update([
      'fee_ratio' => $request->fee_ratio,
      'tip' => $request->tip,
      'enable' => $request->enable
    ]);

    if ($member->wasChanged('enable') && !$member->enable) {
      event(new Kickout($member->id));
    }

    $member->save();
    return success('ok');
  }

  public function storeByAgent(Request $request)
  {
    $exists = User::where('mobile', $request->mobile)->exists();
    if ($exists) {
      fail('手机号已存在');
    }
    $agent = auth()->user();
    if ($request->fee_ratio > $agent->fee_ratio || $request->tip > $agent->tip) {
      fail('参数错误');
    }
    User::create([
      'username' => $request->mobile,
      'mobile' => $request->mobile,
      'role' => 'member',
      'pid' => auth()->id(),
      'fee_ratio' => $request->fee_ratio,
      'tip' => $request->tip,
    ]);

    return success('ok');
  }

  public function show(Member $member)
  {
    //
  }


  public function update(Request $request, $id)
  {
    $user = User::findOrFail($id);
    if ($request->filled('password')) {
      $user->password = bcrypt($request->password);
    }
    $user->enable = $request->enable;
    $user->save();

    return success('ok');
  }

  public function destroy(Member $member)
  {
    //
  }
}
